package com.np.service_demo1.services;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import java.util.Calendar;

public class StartService extends Service {

    private static final String TAG = StartService.class.getSimpleName();
    private Runnable mRunnable;
    private Thread mThread = null;

    @Override
    public void onCreate() {
        Log.i(TAG, "Service onCreate.");
        super.onCreate();

        mRunnable = new Runnable() {
            @Override
            public void run() {
                while (!Thread.interrupted()) {
                    Calendar ca = Calendar.getInstance();
                    int year = ca.get(Calendar.YEAR);
                    int month = ca.get(Calendar.MONTH) + 1;
                    int day = ca.get(Calendar.DAY_OF_MONTH);
                    int hour = ca.get(Calendar.HOUR);
                    int minute = ca.get(Calendar.MINUTE);
                    int second = ca.get(Calendar.SECOND);

                    String time = String.format("%s-%s-%s %s:%s:%s", year, month, day, hour, minute, second);
                    Log.i(TAG, "Current Time: " + time);

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        mThread = new Thread(null, mRunnable, "THREAD_001");
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) {
        Log.i(TAG, "Service onStart.");
        super.onStart(intent, startId);

        if (!mThread.isAlive()) {
            mThread.start();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "Service onStartCommand.");
        return super.onStartCommand(intent,flags,startId);
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "Service onDestroy.");
        super.onDestroy();

        if (mThread.isAlive()) {
            mThread.interrupt();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "Service onBind.");
        return null;
    }
}
